<template>
  <div class="page-binding">
    <van-tabs v-model="active" :class="[!is_mobile ? 'pc-nav' : '']">
      <van-tab
        :disabled="getAction && getAction != 'regist'"
        name="regist"
        :title="$t('locale.pc.binding.t1')"
      >
        <van-form
          @submit="onSubmit"
          :show-error="false"
          class="form"
          ref="form"
        >
          <van-field
            v-model="param.email"
            v-if="web_info.VERIFY_TYPE == 0"
            :label="$t('locale.pc.binding.t2')"
            :placeholder="$t('locale.pc.binding.t3')"
            class="email_box"
            :rules="[
              { required: true, message: $t('locale.pc.binding.t4') },
              {
                pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
                message: $t('locale.pc.binding.t5')
              }
            ]"
          >
            <template #button>
              <van-button
                size="small"
                type="info"
                class="btn-code"
                :disabled="
                  seconds !== 0 ||
                    !/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(
                      param.email
                    )
                "
                native-type="button"
                @click.stop="sendEmailCode"
                >{{
                  seconds !== 0
                    ? seconds + $t("locale.pc.binding.t6")
                    : $t("locale.pc.binding.t7")
                }}</van-button
              >
            </template>
          </van-field>
          <van-field
            v-model="param.code"
            :label="$t('locale.pc.binding.t8')"
            :placeholder="$t('locale.pc.binding.t9')"
            v-if="web_info.VERIFY_TYPE == 0"
            :rules="[
              { required: true, message: $t('locale.pc.binding.t10') },
              { pattern: respond_code, message: $t('locale.pc.binding.t11') }
            ]"
          />
          <van-field
            v-model="param.mobile"
            v-if="web_info.VERIFY_TYPE == 1"
            :label="$t('locale.pc.binding.t12')"
            :placeholder="$t('locale.pc.binding.t13')"
            :rules="[
              { required: true, message: $t('locale.pc.binding.t14') },
              {
                pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
                message: $t('locale.pc.binding.t15')
              }
            ]"
          >
            <template #button>
              <van-button
                size="small"
                type="info"
                class="btn-code"
                :disabled="
                  seconds !== 0 || !/^1(3|4|5|6|7|8|9)\d{9}$/.test(param.mobile)
                "
                native-type="button"
                @click.stop="sendPhoneCode"
                >{{
                  seconds !== 0
                    ? seconds + $t("locale.pc.binding.t6")
                    : $t("locale.pc.binding.t7")
                }}</van-button
              >
            </template>
          </van-field>
          <van-field
            v-model="param.code"
            :label="$t('locale.pc.binding.t8')"
            :placeholder="$t('locale.pc.regist.t49')"
            v-if="web_info.VERIFY_TYPE == 1"
            :rules="[
              { required: true, message: $t('locale.pc.binding.t10') },
              { pattern: respond_code, message: $t('locale.pc.binding.t11') }
            ]"
          />
          <van-field
            v-model="param.password"
            type="password"
            :label="$t('locale.pc.binding.t16')"
            :placeholder="$t('locale.pc.binding.t17')"
            :rules="[
              { required: true, message: $t('locale.pc.binding.t18') },
              {
                pattern: /^[a-zA-Z0-9\S,.!@$^&*-=+`~?:;]{6,16}$/,
                message: $t('locale.pc.binding.t19')
              }
            ]"
          />
          <van-field
            v-model="param._password"
            type="password"
            :label="$t('locale.pc.binding.t20')"
            :placeholder="$t('locale.pc.binding.t21')"
            :rules="[
              { required: true, message: $t('locale.pc.binding.t22') },
              { pattern: password_rule, message: $t('locale.pc.binding.t23') }
            ]"
          />
          <van-field
            v-model="param.inviteCode"
            :label="'邀请码'"
            :placeholder="'请输入邀请码（可选）'"
            v-if="kl_md.KLTDFX == 1"
          />
          <div style="padding:0.3rem;">
            <van-button round block type="info" native-type="submit">{{
              $t("locale.pc.binding.t24")
            }}</van-button>
          </div>
          <!-- <p class="link">
            已有账号？
            <nuxt-link to="/m/login">点击登录</nuxt-link>
          </p> -->
        </van-form>
      </van-tab>
      <van-tab
        :disabled="getAction && getAction != 'login'"
        name="login"
        :title="$t('locale.pc.binding.t25')"
      >
        <van-form class="form">
          <van-field
            v-model="param1.username"
            left-icon="user-o"
            :placeholder="$t('locale.pc.binding.t26')"
            :rules="[{ required: true, message: $t('locale.pc.binding.t27') }]"
          />
          <van-field
            v-model="param1.password"
            type="password"
            left-icon="lock"
            :placeholder="$t('locale.pc.binding.t28')"
            :rules="[{ required: true, message: $t('locale.pc.binding.t29') }]"
          />
        </van-form>
        <div class="lg-btn-box" style="padding: 0.3rem;">
          <van-button round block type="info" @click="handleSuccess(true)">{{
            $t("locale.pc.binding.t30")
          }}</van-button>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import {
  getEmailCode,
  userRegist,
  userLogin,
  userInfoUpdate,
  getSmsCode
} from "~/api/account/user.js";
import { strToHexCharCode, hexCharCodeToStr } from "~/utils/commonfun";
import { mapMutations, mapState, mapActions } from "vuex";
export default {
  components: {},
  data() {
    return {
      param: {
        email: "",
        password: "",
        _password: "",
        mobile: "",
        code: "",
        inviteCode: ""
      },
      param1: {
        username: "",
        password: ""
      },
      active: "",
      interval: null,
      seconds: 0,
      respond_code: new RegExp("")
    };
  },
  computed: {
    ...mapState({
      web_info(state) {
        return state.web_info;
      },
      user_info(state) {
        return state.user_info;
      },
      token(state) {
        return state.token;
      },
      is_mobile(state) {
        return state.is_mobile;
      },
      kl_md(state) {
        return state.kl_md;
      }
    }),
    getAction() {
      return this.$route.query.active;
    },
    getValue() {
      const { value } = this.$route.query;
      let res;
      try {
        res = JSON.parse(value);
      } catch (e) {
        res = value;
      }
      return res;
    },
    password_rule() {
      return new RegExp(this.param.password);
    }
  },
  watch: {},
  methods: {
    ...mapMutations([
      "SET_IS_LOADING",
      "SET_TOKEN",
      "SET_USERINFO",
      "SET_LOGINTYPE",
      "UPDATE_USERINFO"
    ]),
    ...mapActions([
      "initBuyRecord",
      "initBuyCourseRecord",
      "initRtcInfo",
      "initAuthentication",
      "getMineV2QuestionBankList"
    ]),
    async onSubmit() {
      console.log(this.$refs["form"]);
      let res = await this.$refs["form"].validateAll().catch(e => e);
      console.log("res:", res);
      if (res && res.length > 0) {
        return;
      }
      this.SET_IS_LOADING(true);
      const {
        wechat,
        avatar,
        wechatId,
        wechatOpenid,
        mobile,
        password,
        email,
        inviteCode
      } = this.param;
      let regist_params = {
        wechat,
        avatar,
        wechatId,
        wechatOpenid,
        mobile,
        password,
        email
      };
      if (inviteCode) {
        regist_params = {
          ...regist_params,
          inviteCode
        };
      }
      userRegist(regist_params).then(async res => {
        if (res.data.code == 200) {
          let result = await this.handleLogin();
          if (result === "success") {
            this.SET_IS_LOADING(false);

            if (this.is_mobile) {
              this.$toast(this.$t("locale.pc.binding.t31"));
            } else {
              this.$Message.success(this.$t("locale.pc.binding.t31"));
            }
            if (this.is_mobile) {
              this.$router.push("/m");
            } else {
              this.$router.push("/");
            }
          } else {
            this.SET_IS_LOADING(false);
            if (this.is_mobile) {
              this.$toast(this.$t("locale.pc.binding.t32") + result.data.msg);
            } else {
              this.$Message.error(
                this.$t("locale.pc.binding.t32") + result.data.msg
              );
            }
          }
        } else {
          if (this.is_mobile) {
            this.$toast(this.$t("locale.pc.binding.t32") + res.data.msg);
          } else {
            this.$Message.error(
              this.$t("locale.pc.binding.t32") + res.data.msg
            );
          }
        }
      });
    },
    handleLogin() {
      return new Promise(async (res, rej) => {
        let result = await userLogin({
          email: this.param.email,
          password: this.param.password
        });
        if (result && result.data && result.data.code === 200) {
          this.SET_TOKEN(result.headers.authorization);
          this.SET_USERINFO(result.data.data);
          this.initBuyRecord();
          this.initRtcInfo();
          this.initBuyCourseRecord();
          this.initAuthentication();
          this.getMineV2QuestionBankList();
          res("success");
        } else {
          rej(result.data.msg);
        }
      }).catch(e => {
        if (e) {
          this.SET_IS_LOADING(false);
        }
      });
    },
    async handleSuccess(asyncs) {
      let email_reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      let phone_reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
      let login_type = "";
      let params = {
        password: this.param1.password
      };
      if (email_reg.test(this.param1.username)) {
        params = {
          ...params,
          email: this.param1.username
        };
        login_type = "email";
      } else if (phone_reg.test(this.param1.username)) {
        params = {
          ...params,
          account: this.param1.username
        };
        login_type = "mobile";
      } else {
        params = {
          ...params,
          account: this.param1.username
        };
        login_type = "account";
      }
      this.is_show_modal = false;
      this.SET_IS_LOADING(true);
      let result = await userLogin(params);
      if (result && result.data && result.data.code === 200) {
        this.SET_TOKEN(result.headers.authorization);
        this.SET_USERINFO(result.data.data);
        this.SET_LOGINTYPE(login_type);

        if (asyncs) {
          let result1 = await this.updateUser(result.data.data.id).then();
          if (!result1) {
            if (this.is_mobile) {
              this.$toast(this.$t("locale.pc.binding.t33"));
            } else {
              this.$Message.success({
                title: this.$t("locale.pc.binding.t34"),
                content: this.$t("locale.pc.binding.t33")
              });
            }
            return;
          }
        }

        this.initBuyRecord();
        this.initRtcInfo();
        this.initBuyCourseRecord();

        if (this.is_mobile) {
          this.$toast(this.$t("locale.pc.binding.t35"));
        } else {
          this.$Message.success({
            title: this.$t("locale.pc.binding.t34"),
            content: this.$t("locale.pc.binding.t35")
          });
        }
        this.SET_IS_LOADING(false);
        if (this.is_mobile) {
          this.$router.replace("/m");
        } else {
          this.$router.replace("/");
        }
      } else {
        this.SET_IS_LOADING(false);
        if (this.is_mobile) {
          this.$toast(this.$t("locale.pc.binding.t36") + result.data.msg);
        } else {
          this.$Message.error({
            title: this.$t("locale.pc.binding.t34"),
            content: this.$t("locale.pc.binding.t36") + result.data.msg
          });
        }
      }
    },
    sendEmailCode() {
      getEmailCode({
        to: this.param.email
      }).then(res => {
        if (res && res.data && res.data.code == 200) {
          this.respond_code = new RegExp(hexCharCodeToStr(res.data.data.code));
          this.seconds = 60;
          this.cuntDown();
        } else {
          this.$notify({
            type: "danger",
            message: this.$t("locale.pc.binding.t37")
          });
        }
      });
    },
    sendPhoneCode() {
      getSmsCode({
        number: this.param.mobile
      }).then(result => {
        if (result && result.data && result.data.code == 200) {
          this.respond_code = new RegExp(
            hexCharCodeToStr(result.data.data.RequestId)
          );
          this.seconds = 60;
          this.cuntDown();
        } else {
          this.$notify({
            type: "danger",
            message: $t("locale.pc.binding.t37")
          });
        }
      });
    },
    cuntDown() {
      this.interval = setInterval(() => {
        this.seconds--;
        if (this.seconds <= 0) {
          this.seconds = 0;
          clearInterval(this.interval);
        }
      }, 1000);
    },
    async isRedirect() {
      if (
        this.getValue &&
        Object.keys(this.getValue).includes("code") &&
        this.getValue.code == 200
      ) {
        const {
          wechatId,
          password,
          email,
          nickname,
          wechat_avatar,
          wechatOpenid,
          mobile
        } = this.getValue.data;
        // console.log(this.getValue.data);
        //是否登录
        if (this.token && Object.keys(this.user_info).length > 0) {
          const { id } = this.user_info;
          let params = {
            id,
            wechatId,
            avatar: wechat_avatar,
            wechat: nickname,
            wechatOpenid
          };
          let fd = new FormData();
          Object.keys(params).forEach(i => {
            fd.append(i, params[i]);
          });
          let result = await userInfoUpdate(fd);
          if (result && result.data && result.data.code == 200) {
            this.UPDATE_USERINFO(result.data.data);
            if (this.is_mobile) {
              this.$router.replace("/m");
            } else {
              this.$router.replace("/");
            }
          } else if (result && result.data && result.data.code == 1001) {
            // this.$toast(result.data.msg);
            if (this.is_mobile) {
              this.$router.replace('/m/setting?msg='+result.data.msg);
            } else {
              this.$router.replace('/personal?action=user_information&msg='+result.data.msg);
            }
          } else {
            if (this.is_mobile) {
              this.$toast(this.$t("locale.pc.binding.t38") + result.data.msg);
            } else {
              this.$Message.error({
                title: this.$t("locale.pc.binding.t34"),
                content: this.$t("locale.pc.binding.t38") + result.data.msg
              });
            }
          }
        } else {
          //是否已经绑定过
          if (wechatId && (email || mobile) && password) {
            if (email) {
              this.param1 = {
                ...this.param1,
                username: email,
                password
              };
            }
            if (mobile) {
              this.param1 = {
                ...this.param1,
                username: mobile,
                password
              };
            }
            this.handleSuccess(false);
          } else {
            this.param = {
              ...this.param,
              wechat: nickname ? nickname : "",
              avatar: wechat_avatar ? wechat_avatar : "",
              wechatId,
              wechatOpenid
            };
            console.log("params:", this.param);
          }
        }
      }
    },
    async updateUser(id) {
      return new Promise(async (res, rej) => {
        const {
          wechatId,
          password,
          email,
          nickname,
          wechat_avatar,
          wechatOpenid
        } = this.getValue.data;
        let params = {
          id,
          wechatId,
          avatar: wechat_avatar,
          wechat: nickname,
          wechatOpenid
        };
        let fd = new FormData();
        Object.keys(params).forEach(i => {
          fd.append(i, params[i]);
        });
        let result = await userInfoUpdate(fd);
        if (result && result.data && result.data.code == 200) {
          this.SET_USERINFO(result.data.data);
          return res(true);
        } else if (result && result.data && result.data.code == 1001) {
            // this.$toast(result.data.msg);
            if (this.is_mobile) {
              this.$router.replace('/m/setting?msg='+result.data.msg);
            } else {
              this.$router.replace('/personal?action=user_information&msg='+result.data.msg);
            }
          }
        rej(data.data.msg);
      });
    }
  },
  created() {
    if (process.client) {
      // if (this.token && Object.keys(this.user_info).length > 0) {
      //   if (this.is_mobile) {
      //     this.$router.replace("/m");
      //   } else {
      //     this.$router.replace("/");
      //   }
      // }
      this.$nextTick(() => {
        this.active = this.getAction;
        if(this.getValue && this.getValue.data && this.getValue.data.isExist == 1){
          if (this.is_mobile) {
            this.$router.replace('/m/setting?msg=该微信已绑定其他账号');
          } else {
            this.$router.replace('/personal?action=user_information&msg=该微信已绑定其他账号');
          }
        }else{
          this.isRedirect();
        }
      });
    }
  },
  mounted() {}
};
</script>

<style lang="scss">
.page-binding {
  margin: auto;
  max-width: 414px;
  .pc-nav {
    .van-tab {
      font-size: 14px;
      line-height: 44px;
    }
  }
  .form {
    margin: 15px 0;
  }
  .van-cell {
    padding: 10px 16px;
    font-size: 12px;
    .van-field__control {
      font-size: 14px;
    }
  }
  .van-cell:not(:last-child)::after {
    left: 16px;
    border-bottom: 1px solid #ebedf0;
  }
  .van-button {
    height: 44px;
    padding: 0 15px;
    font-size: 14px;
    line-height: 42px;
  }
  .btn-code {
    height: 26px;
    line-height: 24px;
    padding: 0 8px;
  }
}
</style>
